/**
 * Created by XianTao on 2016/11/7
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.wechat.admin.api.restful;

import org.lego.jpa.base.util.DynamicSpecifications;
import org.lego.jpa.base.util.ServletUtil;
import org.lego.jpa.base.vo.ResultVo;
import org.lego.wechat.base.entity.WxCorp;
import org.lego.wechat.base.entity.WxMenu;
import org.lego.wechat.base.service.WxCorpService;
import org.lego.wechat.base.service.WxMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import java.util.List;

@RestController
@RequestMapping(value = "/admin/wechat/menu", method = RequestMethod.POST)
public class WxMenuAdminRestful {
    @Autowired
    private WxMenuService wxMenuService;
    @Autowired
    private WxCorpService wxCorpService;

    @RequestMapping(value = "/list")
    public ResultVo<Page<WxMenu>> list(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
                                       @RequestParam(value = "rows", defaultValue = "10") int pageSize,
                                       ServletRequest request) {
        PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize, ServletUtil.getParametersStartingWithSort(request));
        Specification<WxMenu> specification = DynamicSpecifications.buildSpecification(
                ServletUtil.getParametersStartingWithSearch(request), WxMenu.class);
        return new ResultVo<Page<WxMenu>>(wxMenuService.findAll(specification, pageRequest));
    }

    @RequestMapping(value = "/insertOne")
    public ResultVo<WxMenu> insertOne(@RequestBody WxMenu wxMenu) {
        return new ResultVo<WxMenu>(wxMenuService.saveAndFlush(wxMenu));
    }

    @RequestMapping(value = "/updateOne")
    public ResultVo<WxMenu> updateOne(@RequestBody WxMenu wxMenu) {
        //TODO: after checking valid, then updating entity
        return new ResultVo<WxMenu>(wxMenuService.saveAndFlush(wxMenu));
    }

    @RequestMapping(value = "/publish")
    public ResultVo<Boolean> publish() {
        boolean result = false;
        List<WxCorp> wxCorpList = wxCorpService.findAll();
        if (!ObjectUtils.isEmpty(wxCorpList)) {
            WxCorp wxCorp = wxCorpList.get(0);
            result = wxMenuService.publishMsgMenu(wxCorp.getCorpId(), wxCorp.getAgentId(), wxCorp.getCorpSecret());
        }
        return new ResultVo<Boolean>(result);
    }
}
